package com.dhq.myapp.util.http


import android.util.Log
import com.dhq.myapp.util.LogUtil
import com.dhq.myapp.util.ProjectConstant
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

/**
 * DESC 请求拦截类
 * Created by admin on 2016/11/9.
 */
class MyIntercepter : Interceptor {

    companion object {
        private const val TAG = "MyIntercepter"
    }

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val oriRequest = chain.request()
        val response = chain.proceed(getNewRequest(oriRequest))

//        if (BuildConfig.DEBUG) {
//            responseModify(response)
//        }

        return response
    }

    /**
     * 在请求中添加公用信息
     *
     * @param oriRequest 原始请求信息
     * @return 添加头信息后的新请求
     */
    private fun getNewRequest(oriRequest: Request): Request {
        val builder = oriRequest.newBuilder()

        // 遍历所有拦截器并添加头信息
        ProjectConstant.intercepters.forEach { intercepter ->
            intercepter.addHeaders(builder)
        }

        val newRequest = builder.build()
        // printParams(newRequest.body())

        return newRequest
    }

    /**
     * 修改公用返回信息（调试模式下）
     *
     * @param response 响应对象
     */
    private fun responseModify(response: Response) {
        // 这里不能直接使用response.body().string()的方式输出日志
        // 因为response.body().string()之后，response中的流会被关闭，程序会报错，我们需要创建出一个新的response给应用层处理

        try {
            val responseBody = response.peekBody(1024 * 1024)
            Log.d("infe", "响应头：${response.code}")
            Log.d("infe", "返回数据：${responseBody.string()}")

            LogUtil.json(responseBody.string())

        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}